package meb

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gobjectid"
	"github.com/mosongcc/gotool/gtime"
	"gorm.io/gorm"
	"net/http"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// ProductBuy 产品自动下单跳转到支付界面
func (ctl *Controller) ProductBuy(ctx *gin.Context) (err error) {
	var (
		uid     = ctx.Query("uid")
		prodId  = ctx.Query("prod_id")
		zf      = ctl.ConfigService.Wxpay()
		orderId string
	)
	if prodId == "" {
		err = errors.New("产品编号不能为空")
		return
	}
	defer func() {
		if e := recover(); e != nil {
			err = e.(error)
		}
		if err == nil && orderId == "" {
			err = errors.New("订单ID不能等于空")
		}
		if err != nil {
			ctx.Data(http.StatusOK, gin.MIMEHTML, []byte(fmt.Sprintf(`<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div>%s</div`, err.Error())))
			return
		}
		ctl.cache.Set(uid+prodId, orderId, 1*time.Hour) // 缓存订单ID，给查询接口用
		ctx.Redirect(http.StatusFound, fmt.Sprintf("%s/vpapi/meb/pay/%s", zf.SafeUrl, orderId))
	}()

	// 如果用户存在待支付订单，直接返回
	var order model.Order
	if err = ctl.db.Where(
		"uid = ? and prod_id = ? and status = ? and pay_timeout > ?",
		uid, prodId, model.ORDER_STATUS_PENDING, time.Now().Add(3*time.Minute).Format(gtime.LayoutT14),
	).First(&order).Error; err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return
		}
	}
	if order.OrderId != "" {
		orderId = order.OrderId
		return
	}

	//产品信息
	var prod model.Product
	if err = ctl.db.Where("prod_id = ? and status = ? ", prodId, model.ProductStatus_UP).Take(&prod).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			err = errors.New("产品编号不存在")
			return
		}
		return
	}

	// 当前访问域名
	var domain = ctx.Request.Host
	if host := ctl.cache.Get(ctxHostKey + uid); host != nil {
		domain = host.(string)
	}

	//创建订单
	order = model.Order{
		OrderId:    gobjectid.Hex(),
		Uid:        uid,
		Status:     model.ORDER_STATUS_PENDING,
		TxnDate:    gtime.NowF8(),
		TxnAmt:     prod.UnitPrice,
		PayTimeout: time.Now().AddDate(0, 0, 1).Format(gtime.LayoutT14),
		ProdId:     prod.ProdId,
		ProdName:   prod.ProdName,
		ProdNum:    1,
		ProdPrice:  prod.UnitPrice,
		ProdType:   prod.Type,
		ProdThumb:  prod.Thumb,
		Domain:     domain,
		Ip:         hgin.RemoteIP(ctx),
		Ctime:      gtime.NowF14(),
		Mtime:      gtime.NowF14(),
	}
	err = ctl.db.Create(order).Error
	if err != nil {
		return
	}
	orderId = order.OrderId
	return
}
